package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.dao.MchntApexInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntBaseInfoMapper;
import cc.rengu.igas.bomp.common.dao.OrganizationMapper;
import cc.rengu.igas.bomp.common.dao.impl.MchntApexInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntBaseInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.OrganizationMapperImpl;
import cc.rengu.igas.bomp.common.entity.MchntApexInfo;
import cc.rengu.igas.bomp.common.entity.MchntBaseInfo;
import cc.rengu.igas.bomp.common.entity.Organization;
import cc.rengu.igas.bomp.common.enums.MchntApexPropeytyEnum;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.common.enums.SysParamEnum;
import cc.rengu.igas.bomp.core.realize.WechatActivityService;
import cc.rengu.igas.bomp.core.realize.impl.WechatActivityServiceImpl;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.bean.WechatActivityMchntBean;
import cc.rengu.igas.bomp.facade.request.WechatActivityMchntListQueryRequest;
import cc.rengu.igas.bomp.facade.response.WechatActivityMchntListQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 微信特殊费率商户列表查询
 *
 * @version 1.0
 * @date 2019/08/15
 */
public class WechatActivityMchntListQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        WechatActivityMchntListQueryRequest wechatActivityMchntListQueryRequest = new WechatActivityMchntListQueryRequest();
        ConvertUtil.convertOutput(wechatActivityMchntListQueryRequest);
        return wechatActivityMchntListQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        WechatActivityMchntListQueryRequest wechatActivityMchntListQueryRequest = (WechatActivityMchntListQueryRequest) request;
        WechatActivityMchntListQueryResponse wechatActivityMchntListQueryResponse = new WechatActivityMchntListQueryResponse();
        BizResponse<WechatActivityMchntListQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setResult(wechatActivityMchntListQueryResponse);
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        wechatActivityMchntListQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        wechatActivityMchntListQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        String instId = wechatActivityMchntListQueryRequest.getHeader().getInstId();
        int pageIndex = wechatActivityMchntListQueryRequest.getPageIndex();
        int pageSize = wechatActivityMchntListQueryRequest.getPageSize();
        if (StringUtil.isEmptyOrNull(wechatActivityMchntListQueryRequest.getUserId()) || StringUtil.isEmptyOrNull(String.valueOf(pageIndex)) || StringUtil.isEmptyOrNull(String.valueOf(pageSize))) {
            rglog.error("必填性校验失败!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(pageSize);
        WechatActivityService wechatActivityService = new WechatActivityServiceImpl();

        List<String> activityList = new ArrayList<>();
        if (!StringUtil.isEmptyOrNull(wechatActivityMchntListQueryRequest.getActivityFeeRate())) {
            List<SysParam> sysParamList = SysParamEnum.getSysParamListByParamKey(instId, SysParamEnum.ACTIVITY_RATE.getParamKey());
            if (!CollectionUtils.isEmpty(sysParamList)) {
                sysParamList = sysParamList.stream().filter(item -> wechatActivityMchntListQueryRequest.getActivityFeeRate().equals(item.getParamValue())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(sysParamList)) {
                    for (SysParam sysParam : sysParamList) {
                        activityList.add(sysParam.getParamType());
                    }
                }
            }
        } else {
            activityList = wechatActivityService.getAllActivityList(instId);
        }

        Map<String, String> activityFeeRateMap = new HashMap<>();
        List<String> natureAndIndustryList = new ArrayList<>();
        for (String activityId : activityList) {
            natureAndIndustryList.addAll(wechatActivityService.getActivitySupportNatureAndIndustryType(instId, activityId));

            /*获取活动费率*/
            SysParam rateSysParam = SysParamEnum.getSysParam(instId, activityId, SysParamEnum.ACTIVITY_RATE.getParamKey());
            if (null != rateSysParam) {
                activityFeeRateMap.put(activityId, rateSysParam.getParamValue());
            }
        }
        natureAndIndustryList = natureAndIndustryList.stream().distinct().collect(Collectors.toList());
        StringBuilder support = new StringBuilder();
        for (String natureAndIndustry : natureAndIndustryList) {
            support.append("'").append(natureAndIndustry).append("',");
        }
        support = new StringBuilder(support.substring(0, support.length() - 1));

        MchntBaseInfo mchntBaseInfo = new MchntBaseInfo();
        mchntBaseInfo.setInstId(instId);
        mchntBaseInfo.setMchntName(wechatActivityMchntListQueryRequest.getMchntName());
        mchntBaseInfo.setSignInstId(wechatActivityMchntListQueryRequest.getSignInstId());
        // 设置T_B_MCHNT_SYS_PARAM(商户拓展属性表) 中 活动申请结果(PARAM_VAL) 的查询条件
        mchntBaseInfo.setRemark1(wechatActivityMchntListQueryRequest.getActivityApplyStatus());
        // 设置T_B_MCHNT_BASE_INFO(商户基本信息表) 中 商户性质(MCHNT_NATURE) 的查询条件
        mchntBaseInfo.setMchntNature(support.toString());

        MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
        PageResult pageResult = mchntBaseInfoMapper.selectWechatActivityMchntBaseInfo(mchntBaseInfo, pageInfo);
        if (null == pageResult || null == pageResult.getPageInfo() || CollectionUtils.isEmpty(pageResult.getResult())) {
            rglog.info("根据查询条件查询到0条信息!");
            throw new BizException(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
        }

        MchntApexInfoMapper mchntApexInfoMapper = new MchntApexInfoMapperImpl();
        List<WechatActivityMchntBean> wechatActivityMchntBeanList = new ArrayList<>();
        for (Object mchntInfo : pageResult.getResult()) {
            MchntBaseInfo item = (MchntBaseInfo) mchntInfo;
            WechatActivityMchntBean wechatActivityMchntBean = convMchntInfo(item, mchntApexInfoMapper, activityFeeRateMap);
            wechatActivityMchntBeanList.add(wechatActivityMchntBean);
        }
        wechatActivityMchntListQueryResponse.setWechatActivityMchntBeanList(wechatActivityMchntBeanList);
        wechatActivityMchntListQueryResponse.setPageIndex(pageResult.getPageInfo().getPageIndex());
        wechatActivityMchntListQueryResponse.setPageSize(pageResult.getPageInfo().getPageSize());
        wechatActivityMchntListQueryResponse.setTotalPage(pageResult.getPageInfo().getTotalPage());
        wechatActivityMchntListQueryResponse.setTotalRows(pageResult.getPageInfo().getTotalRows());

        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        WechatActivityMchntListQueryResponse wechatActivityMchntListQueryResponse = (WechatActivityMchntListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(wechatActivityMchntListQueryResponse);
    }

    /**
     * 查询结果转换
     *
     * @param mchntBaseInfo 商户基本信息
     */
    private WechatActivityMchntBean convMchntInfo(MchntBaseInfo mchntBaseInfo, MchntApexInfoMapper mchntApexInfoMapper, Map<String, String> activityFeeRateMap) throws Exception {
        WechatActivityMchntBean wechatActivityMchntBean = new WechatActivityMchntBean();
        BeanUtil.beanCopy(mchntBaseInfo, wechatActivityMchntBean);
        List<MchntApexInfo> mchntSysParamList = mchntApexInfoMapper.selectMchntApexInfoByMchntNo(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());
        if (!CollectionUtils.isEmpty(mchntSysParamList)) {
            List<MchntApexInfo> wActivityStatusMchntApexInfoBeanList = mchntSysParamList.stream().filter(item -> MchntApexPropeytyEnum.ACTIVITY_STATUS.getPropertyKey().equals(item.getPropertyKey())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(wActivityStatusMchntApexInfoBeanList)) {
                wechatActivityMchntBean.setActivityApplyStatus(wActivityStatusMchntApexInfoBeanList.get(0).getPropertyValue());
            }

            List<MchntApexInfo> wApplicationIdMchntApexInfoBeanList = mchntSysParamList.stream().filter(item -> MchntApexPropeytyEnum.APPLICATION_ID.getPropertyKey().equals(item.getPropertyKey())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(wApplicationIdMchntApexInfoBeanList)) {
                wechatActivityMchntBean.setActivityApplyId(wApplicationIdMchntApexInfoBeanList.get(0).getPropertyValue());
            }

            List<MchntApexInfo> wActivityReasonMchntApexInfoBeanList = mchntSysParamList.stream().filter(item -> MchntApexPropeytyEnum.ACTIVITY_REASON.getPropertyKey().equals(item.getPropertyKey())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(wActivityReasonMchntApexInfoBeanList)) {
                wechatActivityMchntBean.setRejectReason(wActivityReasonMchntApexInfoBeanList.get(0).getPropertyValue());
            }

            List<MchntApexInfo> wActivityIdMchntApexInfoBeanList = mchntSysParamList.stream().filter(item -> MchntApexPropeytyEnum.WECHAT_ACTIVITY_ID.getPropertyKey().equals(item.getPropertyKey())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(wActivityIdMchntApexInfoBeanList)) {
                wechatActivityMchntBean.setActivityFeeRate(activityFeeRateMap.get(wActivityIdMchntApexInfoBeanList.get(0).getPropertyValue()));
            }

        }

        /* 获取签约机构名称 */
        OrganizationMapper organizationMapper = new OrganizationMapperImpl();
        Organization organization = organizationMapper.selectOrganizationByPrimaryKey(mchntBaseInfo.getInstId(), mchntBaseInfo.getSignInstId());
        if (null != organization) {
            wechatActivityMchntBean.setSignInstName(organization.getOrgName());
        }

        /*支持活动列表*/
        WechatActivityService wechatActivityService = new WechatActivityServiceImpl();
        List<String> activityList = wechatActivityService.getMchntCanApplyActivity(mchntBaseInfo);
        StringBuilder acticitys = new StringBuilder();
        for (String acticity : activityList) {
            acticitys.append(",").append(acticity);
        }
        acticitys = new StringBuilder(acticitys.substring(1));
        wechatActivityMchntBean.setActivitys(acticitys.toString());

        return wechatActivityMchntBean;
    }
}
